#include "DomTreeWidget.h"

#include <QMenu>


DomTreeWidget::DomTreeWidget(QWidget *parent) :
    QTreeWidget(parent)
{   
    mpTreeProperties = new DomTreeProperties();
    /* TODO: Load properties */
    this->setColumnCount(mpTreeProperties->columnCount());
    this->setHeaderLabels(mpTreeProperties->headerLabels());

    connect(this, SIGNAL(itemClicked(QTreeWidgetItem*,int)),
            this, SLOT(itemClickedSlot(QTreeWidgetItem*,int)));
}

void DomTreeWidget::setRootNode(const QDomNode &rootNode)
{
    this->clear();
    QDomNodeList childNodes = rootNode.childNodes();
    for(int i = 0; i < childNodes.size(); i++)
    {
        if(!mpTreeProperties->nodeTypeVisible(childNodes.at(i).nodeType()))
            continue;

        DomTreeWidgetItem *item = newItem(childNodes.at(i));
        generateItemTree(item, childNodes.at(i));
        this->addTopLevelItem(item);
    }
}

void DomTreeWidget::generateItemTree(DomTreeWidgetItem* parentItem, const QDomNode &parentNode)
{
    // Generate attribute items
    if(mpTreeProperties->nodeTypeVisible(QDomNode::AttributeNode))
    {
        QDomNamedNodeMap attributeList = parentNode.attributes();
        for(int i = 0; i < attributeList.size(); i++)
        {
            DomTreeWidgetItem *item = newItem(attributeList.item(i));
            parentItem->addChild(item);
        }
    }

    QDomNodeList childNodes = parentNode.childNodes();
    for(int i = 0; i < childNodes.size(); i++)
    {
        if(!mpTreeProperties->nodeTypeVisible(childNodes.at(i).nodeType()))
            continue;

        if(mpTreeProperties->flatTextElements()
                && childNodes.at(i).isText())
            continue;

        DomTreeWidgetItem *item = newItem(childNodes.at(i));
        generateItemTree(item, childNodes.at(i));
        parentItem->addChild(item);
    }
}

DomTreeWidgetItem* DomTreeWidget::newItem(const QDomNode &domNode)
{
    DomTreeWidgetItem *item = new DomTreeWidgetItem();
    item->setDomNode(domNode);
    for(int i = 0; i < mpTreeProperties->columnCount(); i++)
    {
        // Set item text
        item->setData(i, Qt::DisplayRole,
                      mpTreeProperties->nodeDisplayText(i, domNode));

        // Set item icon
        item->setData(i, Qt::DecorationRole,
                      mpTreeProperties->nodeDisplayIcon(i, domNode));
    }

    return item;
}

void DomTreeWidget::itemClickedSlot(QTreeWidgetItem * item, int column)
{
    //    QMenu *menu = new QMenu("test");
    //    menu->addAction("asdf");
    //    menu->popup(QPoint(100, 100));
    emit nodeSelected(((DomTreeWidgetItem*)item)->domNode());
}
